package com.example.apidocserver.domain.document.service.impl;

import com.example.apidocserver.domain.document.dao.ApiDocumentDao;
import com.example.apidocserver.domain.document.entity.ApiDocument;
import com.example.apidocserver.domain.document.service.ApiDocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * (ApiDocument)表服务实现类
 *
 * @author makejava
 * @since 2023-02-22 22:56:11
 */
@Service("apiDocumentService")
@Slf4j
public class ApiDocumentServiceImpl implements ApiDocumentService {
    @Resource
    private ApiDocumentDao apiDocumentDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ApiDocument queryById(Integer id) {
        return this.apiDocumentDao.queryById(id);
    }

    /**
     * 查询所有对象
     *
     * @return 查询结果
     */
    @Override
    public List<ApiDocument> queryAll() {
        return this.apiDocumentDao.queryAll();
    }

    /**
     * 根据对象查询
     *
     * @param apiDocument 筛选条件
     * @return 查询结果
     */
    @Override
    public List<ApiDocument> queryByEntity(ApiDocument apiDocument) {
        return this.apiDocumentDao.queryByEntity(apiDocument);
    }

    /**
     * 新增数据
     *
     * @param apiDocument 实例对象
     * @return 实例对象
     */
    @Override
    public ApiDocument insert(ApiDocument apiDocument) {
        this.apiDocumentDao.insert(apiDocument);
        return apiDocument;
    }

    /**
     * 修改数据
     *
     * @param apiDocument 实例对象
     * @return 实例对象
     */
    @Override
    public ApiDocument update(ApiDocument apiDocument) {
        this.apiDocumentDao.update(apiDocument);
        return this.queryById(apiDocument.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.apiDocumentDao.deleteById(id) > 0;
    }

    @Override
    public List<ApiDocument> getReadDocuments(Integer spaceId, boolean writeFlag, boolean publishFlag) {
        // TODO 查询所有有查看权限的文档
        int enable = writeFlag ? 0 : 1;
        int publish = publishFlag ? 1 : 0;
        List<ApiDocument> apiDocuments = this.apiDocumentDao.queryBySpaceId(spaceId, enable, publish);
        if (!CollectionUtils.isEmpty(apiDocuments)) {
            apiDocuments.sort(Comparator.comparing(ApiDocument::getOrderNo));
        }
        return apiDocuments;
    }
}
